<script setup lang="ts">
import type { EChartsOption } from 'echarts';

import { onMounted, onUnmounted, ref, watch } from 'vue';

import * as echarts from 'echarts';

interface ChartProps {
  chartData: {
    seriesData: number[];
    xData: string[];
  };
}

const props = defineProps<ChartProps>();

const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts | null = null;

const getOptions = (): EChartsOption => ({
  backgroundColor: 'transparent',
  grid: {
    top: '12%',
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
    },
  },
  xAxis: {
    type: 'category',
    data: props.chartData.xData,
    axisLine: {
      lineStyle: { color: '#8AB5E9' },
    },
    axisLabel: {
      color: '#fff',
    },
  },
  yAxis: {
    type: 'value',
    splitLine: {
      lineStyle: { color: 'rgba(138, 181, 233, 0.2)' },
    },
    axisLabel: {
      color: '#fff',
    },
  },
  series: [
    {
      type: 'line',
      data: props.chartData.seriesData,
      smooth: true,
      lineStyle: {
        color: '#4caf50',
      },
      itemStyle: {
        color: '#4caf50',
      },
    },
  ],
});

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  chart = echarts.init(chartRef.value);
  chart.setOption(getOptions());
};

// 监听数据变化
watch(
  () => props.chartData,
  () => {
    chart?.setOption(getOptions());
  },
  { deep: true },
);

// 监听窗口大小变化
const handleResize = () => {
  chart?.resize();
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chart?.dispose();
});
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 260px"></div>
</template>